package com.itheima.health.service.impl;

import com.itheima.health.mapper.MemberMapper;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import com.itheima.health.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    // 根据手机号查询会员
    @Override
    public Member findByTelephone(String telephone) {
        return memberMapper.findByTelephone(telephone);
    }
    // 添加会员
    @Override
    public void add(Member member) {
        if(member.getPassword() != null){
            member.setPassword(MD5Utils.md5(member.getPassword()));
        }
        memberMapper.add(member);
    }

    /**
     * 根据月份查询会员数量
     * @param month
     * @return
     */

    @Override
    public List<Integer> findMemberCountByMonth(List<String> month) {
        List<Integer> list = new ArrayList<>();//存储查询到的数据
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM");//格式化日期

        for(String m : month) {
            YearMonth yearMonth = YearMonth.parse(m, formatter);//解析日期
            LocalDate lastDay = yearMonth.atEndOfMonth();//获取当月最后一天
            String validDate = lastDay.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));//格式化日期
            Integer count = memberMapper.findMemberCountBeforeDate(validDate);//查询数据
            list.add(count);
        }
        return list;
    }
}
